package com.lj.dict.properties;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;

/**
 * @author luojing
 * @since 2025/3/13 16:56
 * 字典模块相关配置
 */
@Configuration
@ConfigurationProperties(prefix = "lu-admin.dict")
@Data
public class DictProperties {

    /**
     * 框架默认得包目录，如果不扫描这个包下得枚举字典，管理系统可能会无法使用
     */
    private static final String DEFAULT_PACKAGES = "com.lj";

    /**
     * 主启动类所在的包
     */
    private static final String MAIN_PACKAGES;

    static {
        MAIN_PACKAGES = ClassUtil.getPackage(deduceMainApplicationClass());
    }

    private static Class<?> deduceMainApplicationClass() {
        return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
                .walk(DictProperties::findMainClass)
                .orElse(null);
    }

    private static Optional<Class<?>> findMainClass(Stream<StackWalker.StackFrame> stack) {
        return stack.filter((frame) -> Objects.equals(frame.getMethodName(), "main"))
                .findFirst()
                .map(StackWalker.StackFrame::getDeclaringClass);
    }

    private Set<String> basePackages = CollUtil.newHashSet(MAIN_PACKAGES, DEFAULT_PACKAGES);

    /**
     * 枚举字典扫描得包路径
     */
    private final Set<String> enumDictPackages = new HashSet<>(basePackages);

    public void setEnumDictPackages(Set<String> enumDictPackages) {
        CollUtil.addAll(this.enumDictPackages, basePackages);
        CollUtil.addAll(this.enumDictPackages, enumDictPackages);
    }


}
